package com.weblog.model.utils;

import com.weblog.model.article.Comment;
import com.weblog.model.article.TreeData;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author MaoLin Wang
 * @date 2019/9/2910:21
 */
public class CategoryTreeUtil {


    public static <T extends TreeData<T>> List<T> getTreeList(String parentid, List<T> dataList){
        //存储顶层节点
        List<T> resultList=new ArrayList<>();

        Map<Object,T> categoryMap=new HashMap<>();
        T category;

        for(int i=0;i<dataList.size();i++){
            category=dataList.get(i);
            categoryMap.put(category.getId(),category);
            if(parentid.equals(category.getParentId())){
                resultList.add(category);
            }
        }


        for(int i=0;i<dataList.size();i++){
            category=dataList.get(i);
            T parentCategory=categoryMap.get(category.getParentId());
            if(parentCategory!=null){
                //有父节点
                if(parentCategory.getChildren()==null){
                    parentCategory.setChildren(new ArrayList<>());
                }
                parentCategory.getChildren().add(category);
                categoryMap.put(category.getParentId(),parentCategory);
            }
        }
        return resultList;
    }

    /**
     * 查询待删除评论id集合
     * @param parentid 待查询的顶级id
     * @param dataList 待筛选数据
     * @return
     */
    public static List<String> getDelComment(String parentid, List<Comment> dataList){
        //存储顶层节点
        List<Comment> parentList=new ArrayList<>();

        //最后返回的id集合
        List<String> ids=new ArrayList<>();
        int mapSize= (int) ((dataList.size() / 0.75) +1);
        Map<Object,Comment> commengMap=new HashMap<>(mapSize);
        Comment comment;

        for(int i=0;i<dataList.size();i++){
            comment=dataList.get(i);
            commengMap.put(comment.get_id(),comment);
            if(parentid.equals(comment.getParentid())){
                ids.add(comment.get_id());
                parentList.add(comment);
            }
        }

        dataList.removeAll(parentList);
        for(int i=0;i<dataList.size();i++){
            comment=dataList.get(i);
            if (ids.contains(comment.getParentid())){
                //如果当前评论的父节点在待返回的id集合中，说明该评论是其孩子
                ids.add(comment.get_id());
            }


        }
        return ids;
    }
}
